package com.example.demo.shiro;

import com.example.demo.shiro.realm.CustomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * shiro 工具类
 *
 * @author zhaiding
 * @since 2019/5/19
 */
public class ShiroUtils {

    /**
     * 获取 Subject
     */
    private static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 登出
     */
    public static void logout() {
        getSubject().logout();
    }

    /**
     * 获取 Realm
     */
    private static CustomRealm getCustomRealm() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        return (CustomRealm) rsm.getRealms().iterator().next();
    }

    /**
     * 清理缓存权限
     */
    public static void clearCachedAuthorizationInfo() {
        getCustomRealm().clearCachedAuthorizationInfo();
    }

    /**
     * 清空所有关联认证
     */
    public void clearAllCachedAuthorizationInfo() {
        getCustomRealm().clearAllCachedAuthorizationInfo();
    }

    /**
     * 清除指定用户的关联认证
     *
     * @param username 用户名
     */
    public void clearCachedAuthorizationInfoByUserName(String username) {
        getCustomRealm().clearCachedAuthorizationInfoByUserName(username);
    }

    /**
     * 切换身份
     */
    public static void setSysUser(String user) {
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    /**
     * 获取用户名
     */
    public static String getUserName() {
        return (String) getSubject().getPrincipal();
    }

    /**
     * 获取ip
     */
    public static String getIp() {
        return getSubject().getSession().getHost();
    }

}
